package com.xhx.stream.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

import com.xhx.stream.stream.CustomSendPublisher;

import lombok.extern.slf4j.Slf4j;

/**
 * controller日志
 *
 * @author xhx
 */
@Aspect
@Slf4j
@Component
public class LogAspect {
	@Autowired
	private CustomSendPublisher sendPublisher;

	@Around("execution(* com.xhx.*.controller..*.*(..))")
	public Object logMethodArguments(ProceedingJoinPoint joinPoint) throws Throwable {
		// 获取方法签名
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		// 打印方法名和参数
		Object[] args = joinPoint.getArgs();
		String[] paramNames = signature.getParameterNames();
		StringBuffer sb = new StringBuffer("【" + signature.getName() + "】 ");
		for (int i = 0; i < paramNames.length; i++) {
			Object arg = args[i];
			if (arg instanceof MultipartFile) {
				sb.append(paramNames[i]).append("=").append(((MultipartFile) args[i]).getName()).append(" ");
			} else {
				sb.append(paramNames[i]).append("=").append(args[i]).append(" ");
			}
		}
		sb = sb.deleteCharAt(sb.length() - 1);
		log.info(sb.toString());
		StopWatch watch = new StopWatch();
		watch.start();
		Object res = joinPoint.proceed();
		watch.stop();
		String s = sb.append(",耗时:").append(watch.getTotalTimeMillis()).toString();
		log.info(s);
		sendPublisher.sendLogMsg(s);
		return res;
	}

}